package com.ugoodtech.mdcc.client.Utils;

import org.springframework.data.domain.Page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;


@Data
@AllArgsConstructor
@Builder
public class PageInfoWrapper<T> {

	// 列表页
	private Integer pageIndex;
	// 列表大小
	private Integer pageSize;
	// 当前页的数量
	private Integer size;
	// 列表总页数
	private Integer pages;
	// 总条目数
	private Long total;
	// 数据列表
	private List<T> list;

	public PageInfoWrapper() {
	}

	public PageInfoWrapper(Page pageInfo) {
		list = pageInfo.getContent();
		pageIndex = pageInfo.getNumber();
		pageSize = pageInfo.getSize();
		pages = pageInfo.getTotalPages();
		total = pageInfo.getTotalElements();
		size = pageInfo.getNumberOfElements();
	}

	public static <T> PageInfoWrapper<T> page(Page pageInfo) {
		return new PageInfoWrapper<T>(pageInfo);
	}

	/**
	 * 根据分页索引和分页大小返回空数据
	 *
	 * @param pageNum 分页索引
	 * @param pageSize 分页大小
	 * @return 空的分页信息
	 */
	public static <T> PageInfoWrapper<T> emptyPageInfoWrapper(Integer pageNum, Integer pageSize) {
		PageInfoWrapper<T> pageInfoWrapper = new PageInfoWrapper<T>(pageNum, pageSize, 0, 0, 0L,
				new ArrayList<T>());
		return pageInfoWrapper;
	}

	public static <T> List<T> subListOfPage(Integer pageNum, Integer pageSize, List<T> list) {
		int size = list.size();
		if (pageNum * pageSize <= size) {
			return list.subList((pageNum - 1) * pageSize, pageNum * pageSize);
		}
		if ((pageNum - 1) * pageSize <= size && pageNum * pageSize > size) {
			return list.subList((pageNum - 1) * pageSize, size);
		}
		if ((pageNum - 1) * pageSize > size) {
			return Collections.emptyList();
		}
		return Collections.emptyList();
	}

	public static <T> PageInfoWrapper<T> subListOfPageInfoWrapper(Integer pageNum, Integer pageSize,
			List<T> list) {
		int size = list.size();
		List<T> returnList = new ArrayList<>();
		if (pageNum * pageSize <= size) {
			returnList = list.subList((pageNum - 1) * pageSize, pageNum * pageSize);
		}
		if ((pageNum - 1) * pageSize <= size && pageNum * pageSize > size) {
			returnList = list.subList((pageNum - 1) * pageSize, size);
		}
		if ((pageNum - 1) * pageSize > size) {
			returnList = Collections.emptyList();
		}
		PageInfoWrapper<T> pageInfoWrapper = new PageInfoWrapper<>();
		pageInfoWrapper.setPageSize(pageSize);
		pageInfoWrapper.setPageIndex(pageNum);
		pageInfoWrapper.setTotal((long) list.size());
		pageInfoWrapper.setPages(list.size() / pageSize);
		pageInfoWrapper.setSize(returnList.size());
		pageInfoWrapper.setList(returnList);
		return pageInfoWrapper;
	}

	public static Integer getStartIndex(Integer pageIndex, Integer pageSize) {
		if (Objects.isNull(pageIndex) || Objects.isNull(pageSize)) {
			return null;
		}
		return (pageIndex - 1) * pageSize;
	}

}
